package com.jl.core.netty;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.jl.api.CommonApi;
import com.jl.constants.SysConstants;
import com.jl.core.model.resp.ReConnectResp;
import com.jl.enums.GameStatus;
import com.jl.enums.GameType;
import com.jl.enums.RoomAction;
import com.jl.exception.RRException;
import com.jl.gongniu.model.dto.SzQueueInfo;
import com.jl.mapper.RoomMapper;
import com.jl.model.ChcRoomInfo;
import com.jl.model.CoalitionRoom;
import com.jl.model.Poker;
import com.jl.model.WaCherInfo;
import com.jl.model.gongniu.enums.GongNiuAction;
import com.jl.model.niuniu.enums.NiuAction;
import com.jl.model.req.RoomIntoReq;
import com.jl.model.resp.RoomInfoResp;
import com.jl.model.socket.MyChannelHandlerPool;
import com.jl.model.socket.RoomDetail;
import com.jl.niuniu.model.NiuGameResult;
import com.jl.service.GetUserInfoService;
import com.jl.service.RoomInfoService;
import com.jl.utils.ApplicationContextHolder;
import com.jl.utils.MySocketUtil;
import com.jl.utils.ObjectUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ConcurrentHashMap<Integer, RoomDetail> niuRoomDetailMap = new ConcurrentHashMap<>(); //牛牛房间
    public static ConcurrentHashMap<Integer, RoomDetail> gongNiuRoomDetailMap = new ConcurrentHashMap<>(); //公牛房间
    public static ConcurrentHashMap<ChannelHandlerContext, ChcRoomInfo> chcRoom = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<ChannelHandlerContext, WaCherInfo> waCherInfo = new ConcurrentHashMap<>();


    /**
     * 通道建立
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("------------通道开启！--------------");
    }

    /**
     * 通道断开
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ChcRoomInfo chcRoomInfo = chcRoom.get(ctx);
        WaCherInfo watch = waCherInfo.get(ctx);
        log.info("旧连接{},chcRoomInfo = {}",ctx,chcRoomInfo);
        if (chcRoomInfo!=null){ //玩家断线
            RoomIntoReq roomIntoReq = new RoomIntoReq();
            roomIntoReq.setRoomId(chcRoomInfo.getRoomId());
            roomIntoReq.setGameType(chcRoomInfo.getType());
            RoomDetail roomDetail = getRoomDetail(roomIntoReq);
            RoomInfoResp roomInfoResp = new RoomInfoResp();
            roomInfoResp.setRoomId(chcRoomInfo.getRoomId());
            roomInfoResp.setGameType(chcRoomInfo.getType());
            ObjectUtils objectUtils = ApplicationContextHolder.getBean(ObjectUtils.class);
            CommonApi targetService = objectUtils.getTargetService(roomIntoReq.getGameType());
            try {
                StringRedisTemplate bean = ApplicationContextHolder.getBean(StringRedisTemplate.class);
                Object o = bean.opsForHash().get(SysConstants.GAME_STATUS, chcRoomInfo.getRoomId().toString());
                String status = "";
                if (o!=null){
                    status = o.toString();
                }
                if(roomDetail.getStatus().equals(GameStatus.type2.getId()) || GameStatus.type2.getId().equals(status)){ //如果游戏已经开始或者有人已经发牌。
                    log.info("异常断开!!!!!!!!!!!!!!!!!!");
                    roomInfoResp.setAction(RoomAction.type999.getId());
                    RoomInfoService roomInfoService = ApplicationContextHolder.getBean(RoomInfoService.class);
                    roomInfoService.sendChanel(roomDetail, chcRoomInfo.getUserId().toString(), roomInfoResp);
                    //新建一个socket连接
                    ExecutorService executorService = Executors.newSingleThreadExecutor();
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                targetService.trusteeship(chcRoomInfo,roomDetail,chcRoom);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }finally {
                                executorService.shutdown();
                            }
                        }
                    });
                }else {
                    targetService.quit(chcRoomInfo,roomDetail,ctx);
                }
            } finally {
                log.info("-----------chcRoom remove------------");
                chcRoom.remove(ctx);
            }
        }else if (watch!=null){ //观战断线或退出
            WaCherInfo watcher = MyWebSocketHandler.waCherInfo.get(ctx);
            RoomIntoReq roomIntoReq = new RoomIntoReq();
            roomIntoReq.setRoomId(watcher.getRoomId());
            roomIntoReq.setGameType(watcher.getGameType());
            RoomDetail roomDetail = getRoomDetail(roomIntoReq);
            if (roomDetail.getUserChanelWatcher().get(watcher.getUserId())!=null){ //强退
                ObjectUtils objectUtils = ApplicationContextHolder.getBean(ObjectUtils.class);
                CommonApi targetService = objectUtils.getTargetService(roomIntoReq.getGameType());
                targetService.watcherQuit(watcher,roomDetail,ctx);
                MyWebSocketHandler.waCherInfo.remove(ctx);
            }else {
                MyWebSocketHandler.waCherInfo.remove(ctx);
            }
        }
        log.info("------------通道关闭！------------");
    }

    /**
     * 通道数据读取
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            Map paramMap=getUrlParams(uri);
            //如果url包含参数，需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                request.setUri(newUri);
            }
        }else if(msg instanceof TextWebSocketFrame){  //正常的TEXT消息类型

        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        if (textWebSocketFrame.text().contains("破解")){

        }else {
            RoomIntoReq roomIntoReq = JSONObject.parseObject(textWebSocketFrame.text(), RoomIntoReq.class);
            log.info("收到的请求:{}",roomIntoReq);
            try {
                if (RoomAction.type0.getId().equals(roomIntoReq.getAction())){//观战状态
                    watch(roomIntoReq,channelHandlerContext);
                }else if (RoomAction.type20.getId().equals(roomIntoReq.getAction())){ //加入房间
                    join(roomIntoReq,channelHandlerContext);
                }else if (RoomAction.type99.getId().equals(roomIntoReq.getAction())){ //解散房间
                    dissolution(roomIntoReq,channelHandlerContext);
                }else if (RoomAction.type198.getId().equals(roomIntoReq.getAction())){ //断线重连更新数据
                    updateConnect(roomIntoReq,channelHandlerContext);
                }else { //各个游戏动作独立
                    ConcurrentHashMap<Integer, RoomDetail> map = returnMap(roomIntoReq);
                    RoomDetail roomDetail = map.get(roomIntoReq.getRoomId());
                    ObjectUtils objectUtils = ApplicationContextHolder.getBean(ObjectUtils.class);
                    CommonApi targetService = objectUtils.getTargetService(roomIntoReq.getGameType());
                    targetService.playGame(roomIntoReq,roomDetail,channelHandlerContext,chcRoom,waCherInfo);
                }
            } catch (BeansException e) {
                e.printStackTrace();
                log.info("响应错误");
            }
        }
    }

    private void updateConnect(RoomIntoReq roomIntoReq, ChannelHandlerContext channelHandlerContext) {
        ChcRoomInfo chcRoomInfo = JSONObject.parseObject(roomIntoReq.getActionValue(), ChcRoomInfo.class);
        RoomDetail roomDetail = getRoomDetail(roomIntoReq);
        ChannelHandlerContext old = roomDetail.getUserChanel().get(chcRoomInfo.getUserId());

        chcRoom.remove(old);
        roomDetail.getPlayer().getChannelGroup().remove(old);

        roomDetail.getPlayer().getChannelGroup().add(channelHandlerContext.channel());
        roomDetail.getUserChanel().put(chcRoomInfo.getUserId(),channelHandlerContext);
        chcRoomInfo.setChannelHandlerContext(channelHandlerContext);
        chcRoom.put(channelHandlerContext,chcRoomInfo);

    }

    private void dissolution(RoomIntoReq roomIntoReq, ChannelHandlerContext channelHandlerContext) {
        RoomMapper bean = ApplicationContextHolder.getBean(RoomMapper.class);
        CoalitionRoom coalitionRoom = bean.selectPersonalById(roomIntoReq.getRoomId());
        if (roomIntoReq.getUserId().equals(coalitionRoom.getCreateBy())){
            roomIntoReq.setGameType(coalitionRoom.getGameType());
            ConcurrentHashMap<Integer, RoomDetail> map = returnMap(roomIntoReq);
            RoomDetail detail = map.get(roomIntoReq.getRoomId());
            coalitionRoom.setStatus("0");
            bean.updateByPrimaryKeySelective(coalitionRoom);
            roomIntoReq.setAction(RoomAction.type99.getId());
            roomIntoReq.setActionValue(null);
            sendRoomGroupMessage(toJsonString(roomIntoReq),detail.getPlayer());
            sendRoomGroupMessage(toJsonString(roomIntoReq),detail.getWatcher());
            map.remove(roomIntoReq.getRoomId());
        }else {
            RoomInfoService bean1 = ApplicationContextHolder.getBean(RoomInfoService.class);
            bean1.sendErrorMessage(roomIntoReq, RoomAction.type104,channelHandlerContext);
        }
    }

    private void join(RoomIntoReq roomIntoReq, ChannelHandlerContext channelHandlerContext) {
        RoomMapper bean = ApplicationContextHolder.getBean(RoomMapper.class);
        CoalitionRoom coalitionRoom = bean.selectPersonalById(roomIntoReq.getRoomId());
        if (coalitionRoom!=null){
            roomIntoReq.setGameType(coalitionRoom.getGameType());
            ConcurrentHashMap<Integer, RoomDetail> map = returnMap(roomIntoReq);
            RoomDetail roomDetail = map.get(roomIntoReq.getRoomId());
            if (roomDetail==null){
                roomDetail = new RoomDetail();
            }
            MyChannelHandlerPool watcher = roomDetail.getWatcher();
            Map<Integer, Object> users = roomDetail.getUserInfo();
            //添加观战组
            watcher.getChannelGroup().add(channelHandlerContext.channel());
            roomDetail.getUserChanelWatcher().put(roomIntoReq.getUserId(),channelHandlerContext);
            roomDetail.setWatcher(watcher);
            map.put(roomIntoReq.getRoomId(),roomDetail);
            //发送自己房间用户详情
            roomIntoReq.setAction(RoomAction.type1.getId());
            roomIntoReq.setActionValue(toJsonString(users.values()));
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
            //发送给所有人观战人数
            MySocketUtil.sendWatchCount(roomIntoReq,roomDetail);
        }else {
            RoomInfoService bean1 = ApplicationContextHolder.getBean(RoomInfoService.class);
            bean1.sendErrorMessage(roomIntoReq, RoomAction.type102,channelHandlerContext);
        }
    }

    private String toJsonString(Object obj){
       return JSONObject.toJSONString(obj);
    }


    //发给房间内指定用户组
    private void sendRoomGroupMessage(String message, MyChannelHandlerPool myChannelHandlerPool){
        myChannelHandlerPool.getChannelGroup().writeAndFlush( new TextWebSocketFrame(message));
    }


    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }


    private ConcurrentHashMap<Integer,RoomDetail> returnMap(RoomIntoReq roomIntoReq){
        if (roomIntoReq!=null){
            String gameType = roomIntoReq.getGameType();
            switch (gameType){
                case "1": return niuRoomDetailMap;
                case "2": return gongNiuRoomDetailMap;
            }
        }else {
            throw new RRException("501","加入失败");
        }
        return null;
    }

    private RoomDetail getRoomDetail(RoomIntoReq roomIntoReq){
        ConcurrentHashMap<Integer, RoomDetail> map = returnMap(roomIntoReq);
        return map.get(roomIntoReq.getRoomId());
    }

    //加入房间(观战)
    private void watch(RoomIntoReq roomIntoReq,ChannelHandlerContext channelHandlerContext){
        ConcurrentHashMap<Integer,RoomDetail> concurrentHashMap = returnMap(roomIntoReq);
        RoomDetail roomDetail = concurrentHashMap.get(roomIntoReq.getRoomId());
        if (roomDetail==null){
            roomDetail = new RoomDetail();
        }
        if (CollectionUtil.isEmpty(roomDetail.getUserInfo())){
            roomDetail.setStatus(GameStatus.type1.getId());
        }
        MyChannelHandlerPool watcher = roomDetail.getWatcher();
        Map<Integer, Object> users = roomDetail.getUserInfo();
        StringRedisTemplate bean = ApplicationContextHolder.getBean(StringRedisTemplate.class);
        Object o = bean.opsForHash().get(SysConstants.GAME_PLAYER_STATUS, roomIntoReq.getUserId().toString());
        if (o!=null){ //用户还在游戏中
            log.info("当前游戏未结束,请稍后重试");
            roomIntoReq.setAction(RoomAction.type197.getId());
            roomIntoReq.setActionValue(RoomAction.type197.getDesc());
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
//            log.info("watch api reconnect start");
//            log.info("chcRoom info {}",chcRoom);
//            ChcRoomInfo chcRoomInfo = chcRoom.get(roomDetail.getUserChanel().get(roomIntoReq.getUserId()));
//            log.info("此用户chcRoomInfo {}",chcRoomInfo);
//            chcRoom.remove(chcRoomInfo.getChannelHandlerContext()); //删除旧连接
//            chcRoom.put(channelHandlerContext,chcRoomInfo); //放入新连接
//            roomDetail.reConnect(roomIntoReq.getUserId(),channelHandlerContext);
//            RoomInfoResp roomInfoResp = new RoomInfoResp();
//            BeanUtils.copyProperties(roomIntoReq,roomInfoResp);
//            roomInfoResp.setAction(RoomAction.type998.getId());
//            roomInfoResp.setActionValue(null);
//            MySocketUtil.sendRoomAllMessage(JSONObject.toJSONString(roomInfoResp),roomDetail);
//            //发送自己房间用户详情
//            roomIntoReq.setAction(RoomAction.type1.getId());
//            roomIntoReq.setActionValue(toJsonString(users.values()));
//            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
//            //发送自己手牌信息
//            GetUserInfoService bean = ApplicationContextHolder.getBean(GetUserInfoService.class);
//            List<Poker> userPoker = bean.getUserPoker(roomIntoReq.getUserId());
//            if (GameType.type1.getId().equals(roomIntoReq.getGameType())&&!MySocketUtil.finish(roomDetail,NiuAction.type6.getValue())){ //如果所有人下注完成, 则返回5张, 否则4张
//                if (CollectionUtil.isNotEmpty(userPoker)){
//                    userPoker = userPoker.subList(0,4);
//                }
//                roomIntoReq.setAction(RoomAction.type98.getId());
//                roomIntoReq.setActionValue(toJsonString(userPoker));
//                channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
//            }else if (GameType.type2.getId().equals(roomIntoReq.getGameType())&&!MySocketUtil.finish(roomDetail, GongNiuAction.type4.getValue())){
//
//            }else {
//                roomIntoReq.setAction(RoomAction.type98.getId());
//                roomIntoReq.setActionValue(toJsonString(userPoker));
//                channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
//            }
//            chcRoom.put(channelHandlerContext,new ChcRoomInfo(roomIntoReq.getUserId(),roomIntoReq.getRoomId(),roomIntoReq.getGameType(),channelHandlerContext));
//            log.info("watch api reconnect end");

        }else {
            //添加观战组
            watcher.getChannelGroup().add(channelHandlerContext.channel());
            roomDetail.getUserChanelWatcher().put(roomIntoReq.getUserId(),channelHandlerContext);
            roomDetail.setWatcher(watcher);
            concurrentHashMap.put(roomIntoReq.getRoomId(),roomDetail);
            //添加到观战用户信息
            WaCherInfo waCher = new WaCherInfo();
            waCher.setGameType(roomIntoReq.getGameType());
            waCher.setRoomId(roomIntoReq.getRoomId());
            waCher.setUserId(roomIntoReq.getUserId());
            waCherInfo.put(channelHandlerContext,waCher);
            //发送自己房间用户详情
            roomIntoReq.setAction(RoomAction.type1.getId());
            roomIntoReq.setActionValue(toJsonString(users.values()));
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
            //发送给所有人观战人数
            MySocketUtil.sendWatchCount(roomIntoReq,roomDetail);
        }
    }

    public static ReConnectResp getGamingUser(Integer userId){
        if (CollectionUtil.isNotEmpty(niuRoomDetailMap)){
            for (Map.Entry<Integer,RoomDetail> map : niuRoomDetailMap.entrySet()){
                if (map.getValue().getUserInfo().get(userId)!=null){
                    ReConnectResp reConnectResp = new ReConnectResp();
                    reConnectResp.setUserId(userId);
                    reConnectResp.setGameType(GameType.type1.getId());
                    reConnectResp.setRoomId(map.getKey());
                    return reConnectResp;
                }
            }
        }
        if (CollectionUtil.isNotEmpty(gongNiuRoomDetailMap)){
            for (Map.Entry<Integer,RoomDetail> map : gongNiuRoomDetailMap.entrySet()){
                if (map.getValue().getUserInfo().get(userId)!=null){
                    ReConnectResp reConnectResp = new ReConnectResp();
                    reConnectResp.setUserId(userId);
                    reConnectResp.setGameType(GameType.type2.getId());
                    reConnectResp.setRoomId(map.getKey());
                    return reConnectResp;
                }
            }
        }
        return null;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state().equals(IdleState.READER_IDLE)) {
                log.error("Read Idle");
                RoomIntoReq roomIntoReq = new RoomIntoReq();
                ChcRoomInfo chcRoomInfo = chcRoom.get(ctx);
                WaCherInfo waCherInfo = MyWebSocketHandler.waCherInfo.get(ctx);
                GetUserInfoService getUserInfoService = ApplicationContextHolder.getBean(GetUserInfoService.class);
                RoomInfoService roomInfoService = ApplicationContextHolder.getBean(RoomInfoService.class);
                if (chcRoomInfo!=null){
                    StringRedisTemplate bean = ApplicationContextHolder.getBean(StringRedisTemplate.class);
                    Object o = bean.opsForHash().get(SysConstants.GAME_STATUS, chcRoomInfo.getRoomId().toString());
                    String status = "";
                    if (o!=null){
                        status = o.toString();
                    }
                    roomIntoReq.setUserId(chcRoomInfo.getUserId());
                    roomIntoReq.setRoomId(chcRoomInfo.getRoomId());
                    roomIntoReq.setGameType(chcRoomInfo.getType());
                    RoomDetail roomDetail = getRoomDetail(roomIntoReq);
                    //|| GameStatus.type2.getId().equals(status)
                    if(roomDetail.getStatus().equals(GameStatus.type2.getId())){ //如果游戏已经开始或者有人已经发牌。
                        log.info("Read Idle 异常断开!!!!!!!!!!!!!!!!!!");
                        ObjectUtils objectUtils = ApplicationContextHolder.getBean(ObjectUtils.class);
                        CommonApi targetService = objectUtils.getTargetService(roomIntoReq.getGameType());
                        RoomInfoResp roomInfoResp = new RoomInfoResp();
                        BeanUtils.copyProperties(roomIntoReq,roomInfoResp);
                        roomInfoResp.setAction(RoomAction.type999.getId());
                        RoomInfoService roomInfoService2 = ApplicationContextHolder.getBean(RoomInfoService.class);
                        roomInfoService2.sendChanel(roomDetail, chcRoomInfo.getUserId().toString(), roomInfoResp);
                        //新建一个socket连接
                        targetService.trusteeship(chcRoomInfo,roomDetail,chcRoom);
                    }else {
                        log.info("我是玩家");
                        List<SzQueueInfo> szInfo = roomInfoService.getSzInfo(chcRoomInfo.getRoomId(), SzQueueInfo.class);
                        if (CollectionUtil.isNotEmpty(szInfo)){
                            List<SzQueueInfo> collect = szInfo.stream().filter(a -> a.getId().equals(chcRoomInfo.getUserId())).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(collect)){
                                SzQueueInfo szQueueInfo = collect.get(0);
                                if (szQueueInfo.getBanking().equals("1")){
                                    BigDecimal add = szQueueInfo.getCoin().add(szQueueInfo.getAnte());
                                    getUserInfoService.changeCoin(szQueueInfo.getId(),add);
                                }
                                szInfo.remove(collect.get(0));
                                roomInfoService.setSzInfo(roomIntoReq.getRoomId(),szInfo);
                            }
                        }
                        sendMessageToAll(roomInfoService,roomIntoReq,roomDetail,String.valueOf(roomIntoReq.getUserId()), "1".equals(chcRoomInfo.getType())?NiuAction.type12.getId():GongNiuAction.type13.getId());
                        roomInfoService.quit(roomIntoReq,roomDetail,ctx);
                        roomInfoService.deleteRoomResult(roomIntoReq.getRoomId(),roomIntoReq.getUserId(), NiuGameResult.class);
                        getUserInfoService.deleteUserPoker(roomIntoReq.getUserId());
                    }
                }else if (waCherInfo!=null){
                    log.info("我是观战人");
                    roomIntoReq.setUserId(waCherInfo.getUserId());
                    roomIntoReq.setRoomId(waCherInfo.getRoomId());
                    roomIntoReq.setGameType(waCherInfo.getGameType());
                    ConcurrentHashMap<Integer, RoomDetail> map = returnMap(roomIntoReq);
                    RoomDetail roomDetail = map.get(waCherInfo.getRoomId());
                    roomInfoService.quit(roomIntoReq,roomDetail,ctx);
                    roomIntoReq.setAction("1".equals(waCherInfo.getGameType())?NiuAction.type12.getId():GongNiuAction.type13.getId());
                    roomIntoReq.setActionValue(String.valueOf(roomIntoReq.getUserId()));
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(toJsonString(roomIntoReq)));
                    MySocketUtil.sendWatchCount(roomIntoReq,roomDetail);
                    sendMessageToAll(roomInfoService,roomIntoReq,roomDetail,String.valueOf(roomIntoReq.getUserId()), "1".equals(waCherInfo.getGameType())?NiuAction.type12.getId():GongNiuAction.type13.getId());
                }
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    private void sendMessageToAll(RoomInfoService roomInfoService,RoomIntoReq roomIntoReq,RoomDetail roomDetail,String message,String action){
        RoomInfoResp roomInfoResp = new RoomInfoResp();
        BeanUtils.copyProperties(roomIntoReq,roomInfoResp);
        if (action!=null){
            roomInfoResp.setAction(action);
        }
        roomInfoService.sendChanel(roomDetail, message, roomInfoResp);
    }
}
